package thread;

import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class CallableAndFuture {

	public static void main(String[] args) {
		ExecutorService pool = Executors.newFixedThreadPool(3);
		// Future取得的结果类型和Callable
		// 返回的结果类型必须一致，这是通过泛型来实现的
		Future<String> future = pool.submit(new Callable<String>() {
			@Override
			public String call() throws Exception {
				return "xiongfei";
			}
		});

		try {
			System.out.println("get the return result --" + future.get());
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}

		// CompletionService提交一组Callable任务，对应的take方法返回
		// 已完成的一个Callable任务对应的Future对象
		CompletionService<Integer> completionService = new ExecutorCompletionService<Integer>(pool);
		for (int i = 1; i <= 10; i++) {
			final int seq = i;
			completionService.submit(new Callable<Integer>() {
				@Override
				public Integer call() throws Exception {
					Thread.sleep(new Random().nextInt(5000));
					return seq;
				}
			});
		}

		for (int i = 1; i <= 10; i++) {
			try {
				System.out.println(completionService.take().get());
			} catch (InterruptedException e) {
				e.printStackTrace();
			} catch (ExecutionException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally {
				// ;
			}
		}

		pool.shutdown();
	}

}
